﻿using System;
using System.Web.Mvc;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections;
using System.IO;
using System.Web;
using System.Xml;
using System.Xml.Linq;
using ZFine.Code;
using ZFine.Code.MyTool;

namespace Logiv.WEB.Areas.Project.Controllers
{
    public class UploadifyController : Controller
    {
        #region  保存原图
        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase fileData)//命名和上传控件name 一样
        {
            try
            {
                if ((fileData == null))
                {
                    return Json(new { msg = 0 });
                }
                else
                {
                    var fileExt = System.IO.Path.GetExtension(fileData.FileName).Substring(1);
                    CreateDirectory();//增加文件夹
                    Random r = new Random();
                    var filename = DateTime.Now.ToString("yyyyMMddHHmmss") + r.Next(10000) + "." + fileExt;
                    var FileType = Request["FileType"];
                    var filepath = "";
                    var TrueFilePage = "";
                    var datimeymd = DateTime.Now.ToString("yyyyMMdd");
                    switch (FileType)
                    {
                        case "File": filepath = Path.Combine(Server.MapPath("~/Upload/File"), filename); TrueFilePage = "/Upload/File/"; break;
                        case "Video": filepath = Path.Combine(Server.MapPath("~/Upload/Video"), filename); TrueFilePage = "/Upload/Video/"; break;
                        default:
                            if (!FileHelper.IsExistDirectory(Server.MapPath("~/Upload/original/" + datimeymd)))
                            {
                                FileHelper.CreateDir("Upload\\original\\" + datimeymd + "\\");
                            }
                            filepath = Path.Combine(Server.MapPath("~/Upload/original/"+ DateTime.Now.ToString("yyyyMMdd")), filename);
                            TrueFilePage = "/Upload/original/"+ datimeymd+"/"; break;
                    }
                    if (FileType == "Video")
                    {
                        //判断视频格式
                        string[] strArrFfmpeg = new string[] { "flv", "avi", "mp4", "mov", "3gp" };
                        bool isno = true;
                        foreach (string var in strArrFfmpeg)
                        {
                            if (var == fileExt)
                            {
                                isno = false;
                                break;
                            }
                        }
                        if (isno)
                        {
                            return Json(new { msg = "【上传文件格式不正确，请重新上传】" });
                        }
                    }
                    fileData.SaveAs(filepath);
                    if (FileType == "Video")
                    {
                        //视频转换
                        try
                        {
                            PublicMethod xx = new PublicMethod();
                            //int myzm = xx.MyZm("~/Upload/Video/" + filename, filename);     
                        }
                        catch
                        {
                        }
                    }
                    if (FileType == "Image")
                    {
                        string MinPath = Path.Combine("~/Upload/original/"+ datimeymd, filename);
                        string IsWatermark = Request["IsWatermark"];//是否添加水印
                        IsNoWatermark(IsWatermark, "original", "OriWatermark", filename);//添加水印

                        string Allow = Request["IsMin"];//是否有小图
                        if (Allow == "Allow")
                        {
                            if (!FileHelper.IsExistDirectory(Server.MapPath("~/Upload/Min/" + datimeymd)))
                            {
                                FileHelper.CreateDir("Upload\\Min\\" + datimeymd + "\\");
                            }
                            ToThumbnail(MinPath, "~/Upload/Min/"+ datimeymd + "/" + filename, int.Parse(Request.Params["MinWidth"]), int.Parse(Request.Params["MinHeight"]));
                            IsNoWatermark(IsWatermark, "Min", "MinWatermark", filename);//添加水印
                        }
                        Allow = Request.Params["IsMax"];//是否有大图
                        if (Allow == "Allow")
                        {
                            if (!FileHelper.IsExistDirectory(Server.MapPath("~/Upload/Max/" + datimeymd)))
                            {
                                FileHelper.CreateDir("Upload\\Max\\" + datimeymd + "\\");
                            }
                            ToThumbnail(MinPath, "~/Upload/Max/" + datimeymd + "/" + filename, int.Parse(Request.Params["MaxWidth"]), int.Parse(Request.Params["MaxHeight"]));
                            IsNoWatermark(IsWatermark, "Max", "MaxWatermark", filename);//添加水印
                        }
                    }

                    return Json(new { status = 1, url = TrueFilePage + filename }, "text/html");
                }
            }
            catch (Exception ex)
            {
                return Json(new { msg = -3 });
            }
        }






        /// <summary>
        /// 文件夹
        /// </summary>
        private void CreateDirectory()
        {
            string[] PathList = new string[6];
            PathList[0] = "~/Upload/original";
            PathList[1] = "~/Upload/Max";
            PathList[2] = "~/Upload/Min";
            PathList[3] = "~/Upload/File";//文件
            PathList[4] = "~/Upload/Video";//视频
            PathList[5] = "~/Upload/MemberCenter";//会员中心
            for (int i = 0; i < PathList.Length; i++)
            {
                if (!Directory.Exists(Server.MapPath(PathList[i])))
                {
                    Directory.CreateDirectory(Server.MapPath(PathList[i]));
                }
            }
        }

        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="FilePath">图片地址</param>
        /// <returns></returns>
        public ActionResult DeleteImage(string FilePath)
        {
            int i = 0;
            if (!string.IsNullOrEmpty(FilePath))
            {
                FileHelper.DeleteFile(FilePath);//删除文件
                try
                {
                    FilePath = FilePath.ToLower().Replace("/upload/original/", "").Replace("/upload/file/", "");
                    string[] PathList = new string[6];
                    //PathList[0] = "~/Upload/original";
                    PathList[1] = "~/Upload/Max";
                    PathList[2] = "~/Upload/Min";
                    PathList[3] = "~/Upload/File";//文件
                    PathList[4] = "~/Upload/Video";//视频
                    PathList[5] = "~/Upload/MemberCenter";//会员中心
                    for (i = 0; i < PathList.Length; i++)
                    {
                        if (!string.IsNullOrEmpty(PathList[i]))
                        {
                            // string filePath = Path.Combine(Server.MapPath(PathList[i]), FilePath);
                            // System.IO.File.Delete(filePath);
                        }
                    }
                }
                catch { }
            }
            return Json(new { msg = i });



        }

        #endregion



        public Color tBackground;
        public Color tBorder;
        public Color tShadow;
        public int tQuality;
        public string markPosition;
        /// <summary>
        /// 图片参数预定义
        /// </summary>
        static Hashtable htmimes = new Hashtable();
        internal readonly string AllowExt = ".jpe|.jpeg|.jpg|.png|.tif|.tiff|.bmp|.gif";
        public UploadifyController()
        {
            tBackground = Color.White;
            tBorder = Color.Transparent;
            tShadow = Color.Transparent;
            tQuality = 100;
            markPosition = "左下角";
            #region 图片类型预定义
            htmimes[".jpe"] = "image/jpeg";
            htmimes[".jpeg"] = "image/jpeg";
            htmimes[".jpg"] = "image/jpeg";
            htmimes[".png"] = "image/png";
            htmimes[".tif"] = "image/tiff";
            htmimes[".tiff"] = "image/tiff";
            htmimes[".bmp"] = "image/bmp";
            htmimes[".gif"] = "image/gif";
            #endregion
        }

        #region 下载指定URL图片并保存
        /// <summary>
        /// 下载指定URL的文件并保存到指定目录
        /// </summary>
        /// <param name="strUrl"></param>
        public void DownloadImage(string strUrl, string file)
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            wc.DownloadFile(strUrl, file);
        }
        #endregion

        #region C#自动生成缩略图

        /// <summary>
        /// 获取图像编码解码器的所有相关信息
        /// </summary>
        /// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>
        /// <returns>返回图像编码解码器的所有相关信息</returns>
        private static ImageCodecInfo GetCodecInfo(string mimeType)
        {
            ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo ici in CodecInfo)
            {
                if (ici.MimeType == mimeType) return ici;
            }
            return null;
        }
        /// <summary>
        /// 检测扩展名的有效性
        /// </summary>
        /// <param name="sExt">文件名扩展名</param>
        /// <returns>如果扩展名有效,返回true,否则返回false.</returns>
        private bool CheckValidExt(string sExt)
        {
            bool flag = false;
            string[] aExt = AllowExt.Split('|');
            foreach (string filetype in aExt)
            {
                if (filetype.ToLower() == sExt)
                {
                    flag = true;
                    break;
                }
            }
            return flag;
        }
        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="image">Image 对象</param>
        /// <param name="savePath">保存路径</param>
        /// <param name="ici">指定格式的编解码参数</param>
        private void SaveImage(System.Drawing.Image image, string savePath, ImageCodecInfo ici)
        {
            //设置 原图片 对象的 EncoderParameters 对象
            EncoderParameters parameters = new EncoderParameters(1);
            parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ((long)tQuality));
            image.Save(savePath, ici, parameters);
            parameters.Dispose();
        }
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="sourceImagePath">原图片路径(相对路径)</param>
        /// <param name="thumbnailImagePath">生成的缩略图路径,如果为空则保存为原图片路径(相对路径)</param>
        /// <param name="thumbnailImageWidth">缩略图的宽度（高度与按源图片比例自动生成）</param>
        public void ToThumbnail(string sourceImagePath, string thumbnailImagePath, int thumbnailImageWidth, int thumbnailImageHeight)
        {
            // 1.先检查图片格式等信息
            string ThumbnailImagePath = thumbnailImagePath;
            string SourceImagePath = sourceImagePath;
            string sExt = SourceImagePath.Substring(SourceImagePath.LastIndexOf(".")).ToLower();
            if (SourceImagePath.ToString() == System.String.Empty)
            {
                throw new NullReferenceException("SourceImagePath is null!");
            }
            if (!CheckValidExt(sExt))
            {
                throw new ArgumentException("原图片文件格式不正确,支持的格式有[ " + AllowExt + " ]", "SourceImagePath");
            }
            // 从原图片创建 Image 对象
            System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Server.MapPath(SourceImagePath));
            // 2.计算图片的位置、尺寸等信息
            int tWidth, tHeight, tLeft, tTop;
            double fScale = (double)thumbnailImageHeight / (double)thumbnailImageWidth; // 高度宽度比
            if (((double)image.Width * fScale) > (double)image.Height) // 如果原图比较宽
            {
                tWidth = thumbnailImageWidth;
                tHeight = (int)((double)image.Height * (double)tWidth / (double)image.Width);
                tLeft = 0;
                tTop = (thumbnailImageHeight - tHeight) / 2;
            }
            else
            {
                tHeight = thumbnailImageHeight;
                tWidth = (int)((double)image.Width * (double)tHeight / (double)image.Height);
                tLeft = (thumbnailImageWidth - tWidth) / 2;
                tTop = 0;
            }
            if (tLeft < 0) tLeft = 0;
            if (tTop < 0) tTop = 0;
            if (tBorder != Color.Transparent)
            {
                tWidth -= 2;
                tHeight -= 2;
                tLeft++;
                tTop++;
            }
            if (tShadow != Color.Transparent)
            {
                tWidth -= 1;
                tHeight -= 1;
            }
            //用指定的大小和格式初始化 Bitmap 类的新实例
            //Bitmap bitmap = new Bitmap(ThumbnailImageWidth, num, PixelFormat.Format32bppArgb);
            Bitmap bitmap = new Bitmap(thumbnailImageWidth, thumbnailImageHeight, PixelFormat.Format32bppArgb);
            //从指定的 Image 对象创建新 Graphics 对象
            Graphics graphics = Graphics.FromImage(bitmap);
            //清除整个绘图面并以透明背景色填充
            if (tBackground != Color.Transparent)
            {
                graphics.Clear(tBackground);
            }
            else
            {
                graphics.Clear(Color.Transparent);
            }
            // 添加阴影
            if (tShadow != Color.Transparent)
            {
                Pen shPen = new Pen(tShadow);
                graphics.DrawLine(shPen, new Point(1, thumbnailImageHeight - 1), new Point(thumbnailImageWidth - 1, thumbnailImageHeight - 1));
                graphics.DrawLine(shPen, new Point(thumbnailImageWidth - 1, 1), new Point(thumbnailImageWidth - 1, thumbnailImageHeight - 1));
            }
            // 添加边框
            if (tBorder != Color.Transparent)
            {
                Pen bdPen = new Pen(tBorder);
                if (tShadow != Color.Transparent)
                {
                    graphics.DrawRectangle(bdPen, new Rectangle(0, 0, thumbnailImageWidth - 2, thumbnailImageHeight - 2));
                }
                else
                {
                    graphics.DrawRectangle(bdPen, new Rectangle(0, 0, thumbnailImageWidth - 1, thumbnailImageHeight - 1));
                }
            }
            //在指定位置并且按指定大小绘制 原图片 对象
            graphics.DrawImage(image, new Rectangle(tLeft, tTop, tWidth, tHeight));
            image.Dispose();
            try
            {
                //将此 原图片 以指定格式并用指定的编解码参数保存到指定文件
                string savepath = (ThumbnailImagePath == null ? SourceImagePath : ThumbnailImagePath);
                SaveImage(bitmap, HttpContext.Server.MapPath(savepath), GetCodecInfo((string)htmimes[sExt]));
            }
            catch
            {
                throw;
            }
            finally
            {
                bitmap.Dispose();
                graphics.Dispose();
            }
        }
        #endregion

        #region  C#加水印
        public void IsNoWatermark(string IsWatermark, string OldName, string NewName, string filename)
        {
            try
            {
                if (IsWatermark == "IsWatermark")
                {
                    if (!Directory.Exists(Server.MapPath("~/Upload/" + NewName)))
                    {
                        Directory.CreateDirectory(Server.MapPath("~/Upload/" + NewName));
                    }
                    Watermark("~/Upload/" + OldName + "/" + filename, "~/Upload/" + NewName + "/" + filename);
                }
            }
            catch { }
        }


        public static void Watermark(string oriname, string filename)
        {
            //读取xml
            XmlDocument xmlDoc = new XmlDocument();
            string path = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Content"), "Watermark.xml");
            XDocument xdoc = XDocument.Load(path);
            XElement XRoot = xdoc.Root;
            var isuse = XRoot.Element("isuse").Value;
            var State = XRoot.Element("State").Value;
            var Images = XRoot.Element("Images").Value;
            var Positions = XRoot.Element("Positions").Value;
            var Quality = XRoot.Element("Quality").Value;
            var Transparent = XRoot.Element("Transparent").Value;
            var Widths = XRoot.Element("Widths").Value;
            var Heights = XRoot.Element("Heights").Value;
            var watermarkText = XRoot.Element("watermarkText").Value;
            var fontsize = XRoot.Element("fontsize").Value;
            var fontcolor = XRoot.Element("fontcolor").Value;

            if (isuse == "0")
            {
                //打水印
                Image _serverImage = Image.FromFile(System.Web.HttpContext.Current.Server.MapPath(oriname));
                Bitmap serverImage = new Bitmap(_serverImage);
                _serverImage.Dispose();
                GC.Collect();
                if (State == "0" && !string.IsNullOrEmpty(Images))
                {
                    //图片水印
                    ZFine.Code.MyTool.Watermark.ImageWaterMarkPic(serverImage, System.Web.HttpContext.Current.Server.MapPath(filename), System.Web.HttpContext.Current.Server.MapPath("~" + Images), int.Parse(Positions), int.Parse(Quality), int.Parse(Transparent), int.Parse(Widths), int.Parse(Heights));
                }
                else if (State == "1" && !string.IsNullOrEmpty(watermarkText))
                {
                    //文字水印
                     ZFine.Code.MyTool.Watermark.ImageWaterMarkText(serverImage, System.Web.HttpContext.Current.Server.MapPath(filename), watermarkText, int.Parse(Positions), int.Parse(Quality), "", int.Parse(fontsize), fontcolor);
                }
                else
                {

                }
            }
        }
        #endregion

    }
}
